<template>
	<view class="content">
		<view style="width: 100%;height: 100vh;">
			<video v-if="myvddata.stream" :src="`rtmp://dx11.haoleen.com/videocall/${this.$store.state.user.user.id}`" style="width: 100%;height: 100%;"></video>
		</view>
		<!-- <cover-view
			style="position: fixed;z-index: 9999;top: 0rpx;left: 50rpx;">
			<bgyx-video :currentWebview="this.$scope.$getAppWebview()" :id="id" :name="$store.state.common.videocallinfo.friend_name"></bgyx-video>
		</cover-view> -->
		<cover-view
			style="position: fixed;z-index: 9999;top: 50rpx;right: 50rpx;">
			<video :src="`rtmp://dx11.haoleen.com/videocall/${id}`" style="width: 200rpx;position: fixed;z-index: 9999;height: 360rpx; top: 60rpx;right: 50rpx;" autoplay :show-play-btn="false" object-fit="fill"></video>
		</cover-view>
		<cover-view
			style="position: fixed;z-index: 9999;bottom: 150rpx;left: 0rpx;width: 100%;display: flex;justify-content: center;">
			<cover-image @click="changeaudio" :src="audio ? '/static/images/audioon.png' : '/static/images/audiooff.png'"
				style="width: 110rpx;height: 110rpx;margin-right: 120rpx;"></cover-image>
			<cover-image @click="close" src="/static/images/icon_guad.png"
				style="width: 120rpx;height: 120rpx;"></cover-image>
			<cover-image @click="changev" src="/static/images/qhvv.png"
				style="width: 110rpx;height: 110rpx;margin-left: 120rpx;"></cover-image>
		</cover-view>
	</view>
</template>

<script>
	// 这是用push组件做的 建议使用会议室的webrtc方式 更灵活 效果更好
	import {mapState} from 'vuex'
import utils from '../../../utils'
	export default {
		data() {
			return {
				context: null,
				audio: true,
				video: true,
				mute:false,
				id: 0,
				vtype: false,
				cameraType:"user",
				myvddata:{}
			}
		},
		computed:{
			...mapState({
				data:state=>{
					return state.common.videocallinfo
				}
			})
		},
		onUnload() {
			this.$store.commit(`common/setStatusState`, "normal")
		},
		onLoad({
			id
		}) {
			this.id = id
			
		},
		onReady() {
			this.start({video:true,audio:true})
		},
		methods: {
			changeaudio: function() {
				this.audio = !this.audio
				this.mute = !this.audio
			},
			changev: function() {
				this.vtype = !this.vtype
			},
			cesdataa: function(rtcdata) {
				console.log(`收到的信息`, rtcdata)
				setTimeout(() => {
					rtcdata.unpublish()
				}, 5000)
			},
			start: async function(options) {
				const id = this.$store.state.user.user.id
				const roomId = "videocall"
				const name = this.$store.state.user.user.name
				const pc = new RTCPeerConnection(null);
				pc.addTransceiver('audio', {
					direction: 'sendonly'
				});
				pc.addTransceiver('video', {
					direction: 'sendonly'
				});
				const stream = await navigator.mediaDevices.getUserMedia({
					audio: true,
					video: {
						facingMode: this.cameraType ?? "environment"
					},
				});
				this.cameraType = this.cameraType ?? "environment"
				console.log(stream);
				stream.getTracks().forEach(function(track) {
					pc.addTrack(track);
					if (track.kind === 'audio') {
						if (options.audio === false) {
							track.enabled = false;
						}
					}
					if (track.kind === 'video') {
						if (options.video === false) {
							track.enabled = false;
						}
					}
				});
				let offer = await pc.createOffer();
				await pc.setLocalDescription(offer);
				let session = await new Promise(function(resolve, reject) {
					let data = {
						api: `https://dx11.haoleen.com/rtc/v1/publish/`,
						tid: id,
						streamurl: `webrtc://dx11.haoleen.com/${roomId}/${id}`,
						clientip: null,
						sdp: offer.sdp,
					};
					console.log('Generated offer: ', data);
			
					const xhr = new XMLHttpRequest();
					xhr.onload = function() {
						if (xhr.readyState !== xhr.DONE) return;
						if (xhr.status !== 200) return reject(xhr);
						const data = JSON.parse(xhr.responseText);
						console.log('Got answer: ', data);
						if (data.code === 400) {
							resolve(false);
						}
						return data.code ? reject(xhr) : resolve(data);
					};
					xhr.open('POST', `https://dx11.haoleen.com/rtc/v1/publish/`, true);
					xhr.setRequestHeader('Content-type', 'application/json');
					xhr.send(JSON.stringify(data));
				});
				console.log(session);
				if (session === false) {
					return false;
				}
				await pc.setRemoteDescription(
					new RTCSessionDescription({
						type: 'answer',
						sdp: session.sdp
					}),
				);
			
				function muteAudio(type) {
					stream.getTracks().forEach(function(track) {
						if (track.kind === 'audio') {
							track.enabled = type ?? false;
						}
					});
				}
			
				function muteVideo(type) {
					stream.getTracks().forEach(function(track) {
						if (track.kind === 'video') {
							track.enabled = type ?? false;
						}
					});
				}
				const _this = this
				async function unpublish() {
					try{
						stream.getTracks().forEach(function(track) {
							track.stop();
							stream.removeTrack(track);
						});
						// stream.close()
						pc.close();
					}catch(e){
						//TODO handle the exception
					}
					// _this.dataList = _this.dataList.filter(e => e.id != _this.id)
					// const cid = await getPublishCidById(options.roomId, options.id);
					// console.log(cid);
					// const ret = await axios.delete(
					//   `${process.env.srsUrl}/api/v1/clients/${cid}`,
					// );
				}
			
				const vdata = {
					id: id,
					name: name,
					roomId: roomId,
					pc,
					stream,
					audio: options.audio == false ? false : true,
					video: options.video == false ? false : true,
					user: {
						id,
						name
					},
					muteAudio,
					muteVideo,
					unpublish: unpublish,
				};
				// this.dataList.push(vdata)
				this.myvddata = vdata
			},
			close: function() {
				try{
					this.myvddata.unpublish()
				}catch(e){
					//TODO handle the exception
				}
				this.$socket.send({
					type:"hangoffvideocall",
					data:{
						friend_id:this.data.friend_id,
						friend_name:this.data.friend_name,
						friend_avatar:this.data.friend_avatar
					}
				})
				uni.navigateBack()
			},
		}
	}
</script>

<style scoped>
	.content {
		width: 100%;
	}

	.livePusher {
		width: 100%;
		height: 100vh;
	}
</style>